package util

/*
 * @Desc: 工具类
 * @author: bsyz
 * @version: v1.0.0
 */

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"github.com/PhlexTheCharr/gofurry-cloud-service/common"
	"github.com/PhlexTheCharr/gofurry-cloud-service/roof/env"
	"github.com/bwmarrin/snowflake"
	"github.com/pkg/errors"
	"os"
	"strconv"
	"strings"
	"time"
)

var clusterId, _ = snowflake.NewNode(int64(env.GetServerConfig().ClusterId))

// 雪花算法生成新 ID
func GenerateId() int64 {
	id := clusterId.Generate()
	return id.Int64()
}

// MD5 加密
func CreateMD5(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}

// 判断是否为数字
func IsNumber(str string) bool {
	_, err := strconv.Atoi(str)
	return err == nil
}

// 整形返回时间戳
func GetDigitNow() int {
	now, _ := strconv.Atoi(time.Now().Format(common.TIME_FORMAT_DIGIT))
	return now
}

// 字符串返回时间戳
func GetStrNow() string {
	now := time.Now().Format(common.TIME_FORMAT_DIGIT)
	return now
}

// 格式化时间
func GetDateFormatStr(format string, date time.Time) string {
	dataString := date.Format(format)
	return dataString
}

// 字符串转 int
func String2Int(numString string) (int, error) {
	if strings.TrimSpace(numString) == "" {
		return 0, errors.New("字符串不能为0")
	}
	id, err := strconv.Atoi(numString)
	return id, err
}

// int64 转字符串
func Int642String(i64 int64) string { return strconv.FormatInt(i64, 10) }

// int 转字符串
func Int2String(i int) string { return fmt.Sprintf("%d", i) }

// 字符串转 int64
func String2Int64(numString string) (int64, error) {
	if strings.TrimSpace(numString) == "" {
		return 0, errors.New("参数不能为空")
	}
	id, parseErr := strconv.ParseInt(strings.TrimSpace(numString), 10, 64)
	return id, parseErr
}

// 字符串转float64
func String2Float64(str string) (float64, error) {
	return strconv.ParseFloat(str, 64)
}

// 字符串Unicode转float64
func StringUnicode2Float64(str string) []float64 {
	var floatValues []float64
	// 遍历字符串的每个字符
	for _, char := range str {
		// 获取字符的 Unicode 码值
		codePoint := float64(char)
		// 将码值加入 float64 数组
		floatValues = append(floatValues, codePoint)
	}
	return floatValues
}

// float64 转字符串
func Float642String(f64 float64) string { return fmt.Sprintf("%.0f", f64) }

// 大数
func Decimal(num float64) float64 {
	num, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", num), 10)
	return num
}

// 转换时间戳为时间
func UnixToTime(num int64) string {
	return time.Unix(num, 0).Format(common.TIME_FORMAT_DATE)
}

func FileExists(path string) bool {
	_, err := os.Stat(path)
	return !os.IsNotExist(err) // 不存在返回 false，存在返回 true
}
